import requests
import json,logging


class Location():
    
    ak = "jkFLB4psbeId9MqN51Uzn2IoUsooi5PX"
    baseurl="http://api.map.baidu.com/place/v2/suggestion?query={}&region={}&city_limit={}&output=json&ak={}"
    
    def getLocation(self,key,city=""):
        result={}
        try:
            url = self.baseurl.format(key,city,"true",self.ak)
            response=requests.get(url)
            content = json.loads(response.text)
            logging.debug(content)
            if  content['status'] == 0:
                results = content['result']
                for r in results:
                    location = r['location']
                    if location != {}:
                        result['name'] = r['name']
                        result['location']=r['location']
                        result['city']=r['city']
                        result['district']=r['district']
                        result['cityid']=r['cityid']
                        break
        except:
            pass
        return result
        
        
location = Location()
# print(location.getLocation("丽江花园左岸", "广东省"))
